import {reactive, onBeforeUnmount} from 'vue'
import { designComponent } from '../../../src/use/designComponent';

interface Route {
  path?: string
  hash?: string
  param?: { [k: string]: string }
}


function getRoute(): Route {
  let locationHash = window.location.hash || ''
  console.log({locationHash});

  if (locationHash.charAt(0) === '#') {
    locationHash = locationHash.slice(1)
  }
  console.log({locationHash});

  const [path, hash] = (decodeURIComponent(locationHash)).split('#')
  console.log({path}, {hash});

  return {
    path,
    hash,
  }
}

export const AppNavigator = designComponent({
  name: 'app-navigator',
  props: {
    defaultPath: String,
  },
  provideRefer: true,
  setup({props, setupContext}) {
    const currentRoute = getRoute();
    !currentRoute.path && (currentRoute.path = props.defaultPath);

    const state = reactive({
      route: currentRoute
    })

    const utils = {
      reset: () => {
        const route = getRoute()
        if (!!route) {
          state.route = route
        }
      }
    }

    const handler = {
      hashchange: () => utils.reset()
    }

    const methods = {
      go(path: string) {
        window.location.hash = encodeURIComponent(path)
      }
    }

    const refer = {
      state,
      methods,
    }

    window.addEventListener('hashchange', handler.hashchange)
    onBeforeUnmount(() => window.removeEventListener('hashchange', handler.hashchange))

    return {
      refer,
      render: () => !!setupContext.slots.default ? setupContext.slots.default() : null
    }
  }
})
